import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/register.dart';
import 'package:ichinesereader/models/common/HelpDocItem.dart';
import 'package:ichinesereader/service/user.dart';
import 'package:ichinesereader/utils/StrUtil.dart';
import 'package:reactive_forms/reactive_forms.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:intl/intl.dart';

import '../themes/appTheme.dart';

final RegisterController _registerController = new RegisterController();
final UserServiceProvider _userServiceProvider = new UserServiceProvider();
Color hexStringToHexInt(String hex) {
  if (hex.isEmpty) hex = '#808080';
  hex = hex.replaceFirst('#', '');
  hex = hex.length == 6 ? 'ff' + hex : hex;
  int val = int.parse(hex, radix: 16);
  return Color(val);
}

void showSnackMsg(String msg) {
  Get.snackbar('Message'.tr, '$msg'.tr,
      backgroundColor: Theme.of(Get.context!).primaryColorDark,
      colorText: Get.isDarkMode
          ? Colors.black
          : Theme.of(Get.context!).primaryColorLight,
      snackPosition: SnackPosition.BOTTOM);
}

Future<void> launchInWebViewWithJavaScript(String url) async {
  final box = Hive.box('appconfig');
  var _authtoken = box.get(CacheManagerKey['authtoken'].toString()) ?? '';
  Uri myUri = Uri.parse(url);
  if (!await launchUrl(
    myUri,
    mode: LaunchMode.inAppWebView,
    webViewConfiguration: WebViewConfiguration(
        headers: <String, String>{'authtoken': _authtoken},
        enableJavaScript: true,
        enableDomStorage: true),
  )) {
    throw 'Could not launch $url';
  }
}

String parseDate(int millis) {
  var dt = DateTime.fromMillisecondsSinceEpoch(millis);
  var d12 = DateFormat.yMMMd('en_US').format(dt);
  return d12;
}

String parseDateWithTime(int? millis) {
  if (millis != null) {
    var dt = DateTime.fromMillisecondsSinceEpoch(millis);
    var d12 = DateFormat.yMMMd('en_US').add_jm().format(dt);
    return d12;
  }
  return "-";
}

String parseDateDiff(int millis1, int millis2) {
  var date1 = DateTime.fromMillisecondsSinceEpoch(millis1);
  var date2 = DateTime.fromMillisecondsSinceEpoch(millis2);
  var time = '';
  var diff = date2.difference(date1);
  if (diff.inDays == 1) {
    time = diff.inDays.toString() + ' day'.tr;
  } else {
    time = diff.inDays.toString() + ' days'.tr;
  }
  return time;
}

String getTimeDiff(int difference) {
  int hh = (difference / 1000 / 60 / 60).floor();
  difference -= hh * 1000 * 60 * 60;
  int mm = (difference / 1000 / 60).floor();
  difference -= mm * 1000 * 60;
  int ss = (difference / 1000).floor();

  return difference == 0
      ? "--"
      : "${StrUtil.zeroPad(hh, 2)}:${StrUtil.zeroPad(mm, 2)}:${StrUtil.zeroPad(ss, 2)}";
}

//Datagrid
Container buildDataGridColumnLabel(String labelText) {
  return Container(
    color: Get.isDarkMode ? Colors.transparent : Colors.transparent,
    alignment: Alignment.centerLeft,
    padding: const EdgeInsets.all(6.0),
    child: Text(
      '$labelText'.tr,
      style: TextStyle(
        fontWeight: FontWeight.bold,
        letterSpacing: 1.0,
        color: Get.isDarkMode ? Get.theme.primaryColorDark : Colors.black,
      ),
      overflow: TextOverflow.fade,
    ),
  );
}

dynamic buildHelpCards(List<HelpDocItem> docs, int localNum) {
  return docs.map(
    (item) {
      String _helpText =
          item.helpText != null ? item.helpText!.en.toString() : '';
      if (localNum == 1) {
        _helpText = item.helpText!.cn != null && item.helpText!.cn != ""
            ? item.helpText!.cn.toString()
            : _helpText;
      }
      if (localNum == 2) {
        _helpText = item.helpText!.tc != null && item.helpText!.tc != ""
            ? item.helpText!.tc.toString()
            : _helpText;
      }
      return Container(
        child: Card(
          borderOnForeground: true,
          margin: EdgeInsets.only(top: 15.0),
          elevation: 3.0,
          color: Get.isDarkMode
              ? AppTheme.colors.darkTheme1.withOpacity(0.9)
              : Colors.white.withOpacity(0.8),
          child: Column(
            children: [
              ListTile(
                title: Text(
                  _helpText,
                  style: TextStyle(
                      color: Get.isDarkMode ? Colors.white : Colors.black),
                ),
              ),
              item.image != null && item.image != ''
                  ? Container(
                      margin: EdgeInsets.all(12.0),
                      width: double.infinity,
                      height: 500,
                      color: Colors.blueGrey,
                      child: Image.network(
                        item.image!.toString(),
                        fit: BoxFit.contain,
                      ),
                    )
                  : Text('')
            ],
          ),
        ),
      );
    },
  ).toList();
}

Future<Map<String, dynamic>?> mustUniqueEmail(
    AbstractControl<dynamic> control) async {
  var error = {'unique': false};
  String email = control.value;
  final isAvailable = await _registerController.isEmailAvailable(email);
  if (!isAvailable) {
    control.markAsTouched();
    return error;
  }
  return null;
}

Future<Map<String, dynamic>?> asyncValidatorUniqueUsername(
    AbstractControl<dynamic> control) async {
  final error = {'Usernameunique'.tr: false};
  String userName = control.value;
  final isAvailable = await _userServiceProvider.usernameAvailable(userName);
  if (!isAvailable) {
    control.markAsTouched();
    return error;
  }
  return null;
}
